<?php

namespace app\model\lawcase;

use app\model\BaseModel;

/**
 * 案例文档模型
 * 对应数据表：oa_case_document
 */
class CaseDocument extends BaseModel
{
    /**
     * 数据表名
     * @var string
     */
    protected $name = 'case_document';

    /**
     * 主键名
     * @var string
     */
    protected $pk = 'id';

    /**
     * 字段类型转换
     * @var array
     */
    protected $type = [
        'id' => 'integer',
        'case_id' => 'integer',
        'name' => 'string',
        'type' => 'integer',
        'file_path' => 'string',
        'file_size' => 'integer',
        'file_type' => 'string',
        'description' => 'string',
        'upload_user_id' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];

    /**
     * 可搜索字段
     * @var array
     */
    protected $searchField = ['name', 'description'];

    /**
     * 文档类型
     * @var array
     */
    public const TYPE = [
        1 => '起诉书',
        2 => '答辩书',
        3 => '证据材料',
        4 => '判决书',
        5 => '调解书',
        6 => '其他文书',
    ];

    /**
     * 关联案例
     * @return \think\model\relation\BelongsTo
     */
    public function case()
    {
        return $this->belongsTo('app\model\lawcase\Case', 'case_id', 'id');
    }

    /**
     * 关联上传者
     * @return \think\model\relation\BelongsTo
     */
    public function uploadUser()
    {
        return $this->belongsTo('app\model\admin\User', 'upload_user_id', 'id');
    }

    /**
     * 获取文档列表
     * @param array $params 查询参数
     * @return array
     */
    public function getDocumentList($params = [])
    {
        $where = [];
        
        if (!empty($params['case_id'])) {
            $where[] = ['case_id', '=', $params['case_id']];
        }
        
        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        }
        
        if (!empty($params['upload_user_id'])) {
            $where[] = ['upload_user_id', '=', $params['upload_user_id']];
        }

        return $this->where($where)
            ->with(['case', 'uploadUser'])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $params['limit'] ?? 15,
                'page' => $params['page'] ?? 1,
            ]);
    }

    /**
     * 获取案例文档
     * @param int $caseId 案例ID
     * @param int $type 文档类型
     * @return array
     */
    public function getCaseDocuments($caseId, $type = null)
    {
        $where = [['case_id', '=', $caseId]];
        
        if ($type) {
            $where[] = ['type', '=', $type];
        }

        return $this->where($where)
            ->with(['uploadUser'])
            ->order('type', 'asc')
            ->order('id', 'desc')
            ->select()
            ->toArray();
    }

    /**
     * 上传文档
     * @param array $data 文档数据
     * @return bool
     */
    public function uploadDocument($data)
    {
        $data['create_time'] = time();
        $data['update_time'] = time();
        
        return $this->save($data);
    }

    /**
     * 更新文档信息
     * @param int $id 文档ID
     * @param array $data 更新数据
     * @return bool
     */
    public function updateDocument($id, $data)
    {
        $data['update_time'] = time();
        
        return $this->where('id', $id)->update($data);
    }

    /**
     * 删除文档
     * @param int|array $ids 文档ID
     * @return bool
     */
    public function deleteDocument($ids)
    {
        if (is_array($ids)) {
            $documents = $this->where('id', 'in', $ids)->select();
            foreach ($documents as $document) {
                if (!empty($document['file_path']) && file_exists($document['file_path'])) {
                    @unlink($document['file_path']);
                }
            }
            return $this->where('id', 'in', $ids)->delete();
        } else {
            $document = $this->find($ids);
            if ($document && !empty($document['file_path']) && file_exists($document['file_path'])) {
                @unlink($document['file_path']);
            }
            return $this->where('id', $ids)->delete();
        }
    }

    /**
     * 获取文档统计
     * @param int $caseId 案例ID
     * @return array
     */
    public function getDocumentStats($caseId)
    {
        $stats = $this->where('case_id', $caseId)
            ->field('type, COUNT(*) as count, SUM(file_size) as total_size')
            ->group('type')
            ->select()
            ->toArray();

        $result = [
            'total_count' => 0,
            'total_size' => 0,
            'type_stats' => []
        ];

        foreach ($stats as $stat) {
            $result['total_count'] += $stat['count'];
            $result['total_size'] += $stat['total_size'];
            $result['type_stats'][$stat['type']] = [
                'count' => $stat['count'],
                'size' => $stat['total_size']
            ];
        }

        return $result;
    }

    /**
     * 格式化文件大小
     * @param int $size 文件大小（字节）
     * @return string
     */
    public function formatFileSize($size)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $unit = 0;
        
        while ($size >= 1024 && $unit < count($units) - 1) {
            $size /= 1024;
            $unit++;
        }
        
        return round($size, 2) . ' ' . $units[$unit];
    }

    /**
     * 搜索器：按案例ID搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchCaseIdAttr($query, $value)
    {
        $query->where('case_id', $value);
    }

    /**
     * 搜索器：按文档类型搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchTypeAttr($query, $value)
    {
        $query->where('type', $value);
    }

    /**
     * 搜索器：按上传者搜索
     * @param \think\db\Query $query
     * @param int $value
     */
    public function searchUploadUserIdAttr($query, $value)
    {
        $query->where('upload_user_id', $value);
    }

    /**
     * 搜索器：按名称搜索
     * @param \think\db\Query $query
     * @param string $value
     */
    public function searchNameAttr($query, $value)
    {
        $query->where('name', 'like', '%' . $value . '%');
    }
}